import 'rxjs/add/operator/switchMap';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import 'rxjs/add/operator/switchMap';
declare var $:any;
var mqtt = require('mqtt');
@Component({
  selector: 'my-app',
  template: `
  <div class="chat">
    <img  src="/assets/img/timg.png" alt="Stage-logo" />
    <div class="chatMessage" id="setChat">
    <br/>
    <ul>
      <li *ngFor="let mess of messages" [ngClass]="mess.classType">
       {{mess.message}}
      </li>
    </ul> 
    </div>
     <br/>
     <div class="chatInput">
        <input  type="text" class="form-control"[(ngModel)]="message" placeholder="按enter或点击按钮发送"/>
     </div>
      <br/>
      <div class="chatButton">
      <button class="bttn-stretch bttn-sm bttn-primary"  (click)="pub()" >发送</button>
      <button class="bttn-stretch bttn-sm bttn-primary" data-toggle="modal" data-target="#myModal" >修改昵称</button>
      </div>
  </div>
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title" id="myModalLabel">输入昵称</h4>
            </div>
            <div class="modal-body">
              <label for="name">名称</label>
              <input type="text" class="form-control" id="name" placeholder="请输入名称" [(ngModel)]="nickname">
              </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" (click)="changeNickname()">提交更改</button>
            </div>
        </div>
    </div>
</div>
    `
})
export class ChatComponent implements OnInit {
  nickname = '罗志祥' + Math.random().toString(30).substr(2, 3);
  options;
  title;
  message;
  client;
  messages = [];
  constructor(
    private route: ActivatedRoute,
    private location: Location
  ) { }
  sub(): void {
    this.client.subscribe(this.title.value.id);
    this.client.subscribe(this.title.value.id + "ShowRosarugosa");
    this.client.publish(this.title.value.id + "ShowRosarugosa", this.nickname + "上线啦");
    this.receive();
  }
  pub(): void {
    this.client.publish(this.title.value.id, this.client.options.clientId + "^@&" + this.message + "^@&" + this.client.options.username);
    this.message = '';
  }
  receive(): void {
    var _this = this;
    this.client.on("message", function (topic, message) {
      if (topic == _this.title.value.id) {
        var messageString = message.toString();
        var mes = messageString.split("^@&", 3);
        console.log(mes)
        if (mes[0] == _this.client.options.clientId) {
          var temp = {
            classType: 'myMessage',
            message: _this.nickname + ": " + mes[1]
          }
          _this.messages.push(temp);
        } else {
          var temp = {
            classType: 'otherMessage',
            message: mes[2] + ": " + mes[1]
          }
          _this.messages.push(temp);
        }
      } else {
        var usertemp = {
          classType: 'badge',
          message: message
        }
        _this.messages.push(usertemp);
      }
      // this.client.end();
    });
  }
  ngAfterViewChecked() {
    this.setlocation();
  }
  ngOnInit(): void {
    this.title = this.route.params;
    this.connect();
  }
  connect(): void {
    var id = 'Rosarugosa' + Math.random().toString(16).substr(2, 8);
    var test = this.title.value.id + "ShowRosarugosa"
    var myOptions = {
      clientId: id,
      username: this.nickname,
      will: {
        topic: test,
        payload: this.nickname + "下线了",
        qos: 0,
        retain: false
      }
    }
    var clientmqtt = mqtt.connect("ws://112.74.91.17:8001", myOptions);
    this.client = clientmqtt;
    this.options = myOptions;
    this.sub();
    this.listen();
  }
  goBack(): void {
    this.location.back();
  }
  listen(): void {
    var _this = this;
    document.onkeydown = function (event) {
      var e = event || window.event || arguments.callee.caller.arguments[0];
      if (e && e.keyCode == 13) { // enter 键
        _this.pub();
      }
    };
  }
  changeNickname(): void {
    this.client.end();
    this.connect();
    $('#myModal').modal('hide');
  }
  setlocation(): void {
    var div = document.getElementById("setChat");
    div.scrollTop = div.scrollHeight;
  }
}